package com.qf.mybatisplus.utils.excel;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.qf.mybatisplus.bean.entity.UserDemo;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class TestExcelDemo {

    @Test
    public void HutollDownLoadExcelTest() throws FileNotFoundException {
        //1.创建一个Excel写出工具Writer
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //2.模拟List数据
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        //3.将list数据输出到excel中
        writer.write(list);
        //4. 将填充数据后的excel文件保存在d盘文件中.
        writer.flush(new FileOutputStream("D:\\qianfeng\\mybatisPlusFile\\testExel.xlsx"));
    }

    @Test
    public void testExport() throws FileNotFoundException {

        //1. 创建一个Excel写出工具Writer
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //2. 设置别名
        writer.addHeaderAlias("id","编号");
        writer.addHeaderAlias("name","名字");

        //3. 先输出一行标题(参数1是跨列数, 从0开始. 参数2 是标题字符串)
        writer.merge(3,"标题");
        //4. 模拟list集合数据
        List<UserDemo> users = getUsers();
        //5. 将users数据输出到excel文件中.
        writer.write(users,true);// true表示并输出标题。
        //6. 将填充数据后的excel文件保存在d盘文件中.
        writer.flush(new FileOutputStream("D:\\qianfeng\\mybatisPlusFile\\testExportExel.xlsx"));
    }

    private List<UserDemo> getUsers(){
        List<UserDemo> list = new ArrayList<>();
        list.add(new UserDemo(1001,"张三"));
        list.add(new UserDemo(1002,"张三"));
        list.add(new UserDemo(1003,"张三"));
        list.add(new UserDemo(1004,"张三"));
        return list;
    }

    @Test
    public void HutollUploadExcelTest() throws FileNotFoundException {
        //1. 创建一个Excel读取工具reader
        ExcelReader reader = ExcelUtil.getReader(new FileInputStream("D:\\qianfeng\\mybatisPlusFile\\testExportExel.xlsx"));
        //2. 设置读取的数据的别名和封装的实体的属性对应关系.
        reader.addHeaderAlias("编号","id");
        reader.addHeaderAlias("名字","name");

    /*
        reader读取excel文件数据
        参数说明
            headerRowIndex: 映射的数据标题在第几行, 从0开始算.
            startRowIndex: 实际读取的数据从第几行开始, 从0开始算.
            class: 读取的数据封装成什么类型的对象

     */
        List<UserDemo> users = reader.read(1, 2, UserDemo.class);
        // 输出返回的users集合
        System.out.println(users);
        // 输出users的大小.
        System.out.println(users.size());
    }


}
